package com.example.weiwing.home.study;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.example.weiwing.R;
import com.example.weiwing.config.WeiWingConfig;
import com.example.weiwing.entity.Article;
import com.example.weiwing.entity.Course;
import com.example.weiwing.entity.User;
import com.example.weiwing.util.SpUtils;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.Source;

import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class CoursePlayer extends AppCompatActivity {
    private static final String TAG = "CoursePlayer";
    private RecyclerView recyclerView;
    private CourseSeriesAdapter lessonAdapter;
    private Course course;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private IjkMediaPlayer player;

    private Handler mHandler;

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.release();
        }
        IjkMediaPlayer.native_profileEnd();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);
        findViewById(R.id.addLesson).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CoursePlayer.this, CutFileUploadActivity.class);
                intent.putExtra("courseId", String.valueOf(course.getCourseId()));
                startActivity(intent);


            }
        });

        // TODO:如果课程为空，应该显示特殊的页面，有时间再做


        // 跳转页面后，获取课程 Course ，通过该 Course 加载对应的视频课程
        // 这是获取到的 Course 实体，测试使用
//        course = (Course) getIntent().getSerializableExtra("courseEntity");
        new getCourseThread(getIntent().getStringExtra("courseId")).start();

        mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {

                    lessonAdapter = new CourseSeriesAdapter(course.getLessonList());
                    recyclerView.setAdapter(lessonAdapter);
                    // 设置每一集 lesson 的点击事件
                    lessonAdapter.setOnItemClickListener(new CourseSeriesAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Toast.makeText(CoursePlayer.this, "你点击了" + course.getLessonList().get(position).getLessonName(), Toast.LENGTH_SHORT).show();
                            releasePlayer();
                            playVideo(WeiWingConfig.getUrl() + course.getLessonList().get(position).getVideoUrl());
                        }
                    });
                    playVideo(WeiWingConfig.getUrl() + course.getLessonList().get(0).getVideoUrl());
                }
            }
        };

        // 以下是视频播放部分代码
        mSurfaceView = findViewById(R.id.surface_view);
        mSurfaceHolder = mSurfaceView.getHolder();
        // 设置分集的 RecyclerView
        recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);

        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                //IjkMediaPlayer.loadLibrariesOnce(null);
                //IjkMediaPlayer.native_profileBegin("libijkplayer.so");


//                player = new IjkMediaPlayer();
//                mSurfaceHolder = mSurfaceView.getHolder();
//                playVideo(WeiWingConfig.getUrl() + course.getLessonList().get(0).getVideoUrl());
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                releasePlayer();
            }
        });


    }


    public class getCourseThread extends Thread {
        private String id;

        public getCourseThread(String id) {
            this.id = id;
        }

        @Override
        public void run() {
            super.run();
            HttpRequest.build(CoursePlayer.this, WeiWingConfig.getUrl() + "/course/" + id)
                    .addHeaders("token", SpUtils.getString(CoursePlayer.this, "token"))
                    .setResponseListener(new ResponseListener() {
                        @Override
                        public void onResponse(String response, Exception error) {
                            // 处理加载结果
                            if (error == null) {
                                JSONObject jsonObject = JSON.parseObject(response);
                                if (jsonObject.getInteger("code") == 200) {
                                    course = jsonObject.getObject("data", new TypeReference<Course>() {
                                    });
                                    mHandler.obtainMessage(1).sendToTarget();
                                } else {
                                    Toast.makeText(CoursePlayer.this, "请求失败", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(CoursePlayer.this, "请求失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }).doGet();
        }
    }

    private void playVideo(String url) {
        try {
            player = new IjkMediaPlayer();
            player.setDisplay(mSurfaceHolder);
            player.setDataSource(url);
            player.prepareAsync();
            player.setOnPreparedListener(mp -> {
                // 视频准备完成后开始播放
                player.start();
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void releasePlayer() {
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
    }

}
